<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2019/1/2  16:37
 */
namespace app\driver\logic;
use app\driver\BaseModel;
use think\Cache;
use think\Db;
class Order extends  BaseModel
{

    //检测参数是否已传
    protected $ParameterDetection = [
        'orderList'=>['send_status','time'],
        'orderInfo'=>['id'],
        'updateSendstatus'=>['id'],
        'reply'=>['id','content']
    ];

    //订单列表
    public function orderList()
    {
        $uid = $this->user['id'];
//        die($uid);
        $page=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $limit=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $status = $this->requestData['send_status'];
        $time = isset($this->requestData['time'])?$this->requestData['time']:'1';
        $today = strtotime(date("Y-m-d"),time());//1547049600
        $zuotian = strtotime(date("Y-m-d"),time())-24*60*60;//1546963200
//        var_dump($today);
//        var_dump($zuotian);
//        die;
        switch($time){
            case '1':
                $where['send_time'] = ['>=',$today];
                break;
            case '2':
                $where['send_time'] = ['<',$today];
                $where['send_time'] = ['>=',$zuotian];
                break;
            case '3':
                $where['send_time'] = ['<',$zuotian];
                break;
            default:
                $where['send_time'] = ['>=',$today];
        }
//        die;
        switch ($status) {
            case '2':
                //进行中订单
                $where['status'] = '1';
                break;
            case '3':
                //已完成订单
                $where['status'] = '2';
                break;
            default:
                //进行中订单
                $where['status'] = '1';
                break;
        }
        $where['driver_id'] = $this->user['id'];
        //订单数量
        $result = $this->getDrivarOrder($uid,$where,$page,$limit);
        return $result;
    }

    //订单详情
    public function orderInfo()
    {
        $uid = $this->user['id'];//订单id
        $id = isset($this->requestData['id'])?$this->requestData['id']:'';
        if(!$id)return ['message'=>'id必传'];
        $sel = db('order')->where(['id'=>$id])->find();
        if(empty($sel))return ['message'=>'非法id!'];
        $sel = db('driver_order_info')->alias('i')
            ->join('driver_order o','o.id=i.driver_order_id')
            ->where('i.order_id='.$id)
            ->field('o.driver_id')
            ->find();
//        echo db('driver_order_info')->getLastSql();die;
        if($sel['driver_id'] !=0 && $sel['driver_id'] != $uid)return ['message'=>'无权查看'];

        $order = db('order')->alias('or')
            ->join('shop s','s.id=or.shop_id')
            ->where(['or.id'=>$id])
            ->field('or.id,or.order_sn,or.address,or.mobile,or.status,or.send_status,or.create_time,or.send_time,or.end_time,or.preference,or.shop_id,s.shopname,s.headimage')
            ->find();

        if(empty($order))return ['message'=>'订单不存在!'];

        $order['create_time'] = date('Y-m-d h:i:s',$order['create_time']);
        $order['send_time'] = date('Y-m-d h:i:s',$order['send_time']);
        $order['end_time'] = date('Y-m-d h:i:s',$order['end_time']);
        $order['headimage'] = IMG_PATH.$order['headimage'];
        $order_goods = db('order_goods')->where(['order_id'=>$id])->field('goods_id,goods_num,goods_name,goods_image')->select();
        foreach($order_goods as $k=>&$v){
            $v['goods_image'] = IMG_PATH.$v['goods_image'];
        }
        $result['order_info']= $order;
        $result['order_info']['goods'] = $order_goods;
        return $result;
    }

    //开始配送
    public function startSend()
    {
        $id = $this->requestData['id'];//订单id
        $uid = $this->user['id'];//司机id

        $order = db('order')->where(['id'=>$id])->find();
        $driver_order_id = db('driver_order_info')->where(['order_id'=>$id])->value('driver_order_id');
        if(empty($order) || empty($driver_order_id))return ['message'=>'非法id!'];
//
        $driver_order = db('driver_order')->where(['id'=>$driver_order_id])->find();
        if($order['send_status'] != '1' && $order['type'] != '2' && $driver_order['driver_id'] == $uid)return ['message'=>'无权操作!'];

        $data['send_status'] = '2';
        $data['startsend_time'] = TIMESTAMP;

        $res = db('order')->where(['id'=>$id])->update($data);
        if(!$res) return array('message' => '操作失败');

    }

    //司机确认收货
    public function updateSendstatus()
    {
        $id = $this->requestData['id'];//订单id
        $uid = $this->user['id'];//司机id
        $order = db('order')->where(['id'=>$id])->find();
        $driver_order_id = db('driver_order_info')->where(['order_id'=>$id])->value('driver_order_id');
        if(empty($order) || empty($driver_order_id))return ['message'=>'非法id!'];

        $driver_order = db('driver_order')->where(['id'=>$driver_order_id])->find();
        if($order['send_status'] != '2' && $order['type'] != '2' && $driver_order['driver_id'] == $uid)return ['message'=>'无权操作!'];
//        die;
        $distance = db('driver_order_info')->where(['order_id'=>$id])->value('distance');

        Db::startTrans();
        try {
            //2确认收货，更新order表数据
            $data['send_status'] = '3';
            $data['end_time'] = TIMESTAMP;
            //司机配送收入
            $start_price = db('config')->where(['id' => 9])->find();
            if(empty($start_price)){$start_price = 0;}else{
                $start_price = floatval($start_price);
            }
            $start_number = db('config')->where(['id' => 10])->find();
            if(empty($start_number)){$start_number = 0;}else{
                $start_number = floatval($start_number);
            }
            $over_price = db('config')->where(['id' => 11])->find();
            if(empty($over_price)){$over_price = 0;}else{
                $over_price = floatval($over_price);
            }
            $money = $start_price+($distance-$start_number)*$over_price;
//                $send_free = $order['send_fee'] * ($system_balance/100);
//                $send_free = substr(sprintf("%.3f",$send_free),0,-1);
//                $send_free_total = $order['send_fee']-$send_free;
            $driver_balance = [
                'driver_id' => $driver_order['driver_id'],
                'shop_id' => $order['shop_id'],
                'money' => $money,
                'order_id' => $order['id'],
                'commission_record' => 0,//回扣金额
                'create_time' => TIMESTAMP
            ];

            db('driver_balance')->insert($driver_balance);
//            throw new \Exception('a');

            $res = db('order')->where(['id'=>$id])->update($data);
            if(!$res)  throw new \Exception('操作失败');
            //判断，更新司机订单
            $this->is_empty_unfinish_order($id);
        }catch (\Exception $e) {
            Db::rollback();
            return array('message' => $e->getMessage());
        }

        return [];
    }

    //我的评分
    public function comments()
    {
        $uid = $this->user['id'];
//        die($uid);
        $page=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $limit=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $where['c.driver_id'] = $uid;
        $count = db('driver_order_comment')->where(['driver_id'=>$uid])->count();
        $list = db('driver_order_comment')->alias('c')
            ->join('order o','o.id=c.order_id','LEFT')
            ->join('shop s','s.id=o.shop_id','LEFT')
            ->field('c.*,o.send_time,s.shopname,s.headimage')
            ->where($where)
            ->order('c.id desc')
            ->page($page,$limit)
            ->select();
        foreach($list as $key=>&$value){
//            //购买多少种商品
//            $goods_count = db('order_goods')->where(['order_id'=>$value['id']])->count();
//            $order[$key]['goods_count'] = $goods_count;
            $value['headimage'] = IMG_PATH.$value['headimage'];
            $value['send_time'] = date('Y-m-d h:i:s',$value['send_time']);
            //订单商品
            $goods = db('order_goods')->where(['order_id'=>$value['order_id']])->field('goods_id,goods_num,goods_name,goods_image')->select();
            foreach($goods as $k=>&$v){
                $v['goods_image'] = IMG_PATH.$v['goods_image'];
            }
            $value['goods'] = $goods;
        }
        $result['list'] = $list;
        $result['count'] = $count;
        $result['page_num'] = $page;
        $result['page_limit'] = $limit;
        return $result;
    }

    public function commentInfo()
    {
        $uid = $this->user['id'];
        $comment_id = $this->requestData['id'];
        $where['c.driver_id'] = $uid;
        $where['c.id'] = $comment_id;
        $list = db('driver_order_comment')->alias('c')
            ->join('order o','o.id=c.order_id','LEFT')
            ->join('shop s','s.id=o.shop_id','LEFT')
            ->field('c.*,o.send_time,s.shopname,s.headimage')
            ->where($where)
            ->order('c.id desc')
            ->find();
        $list['headimage'] = IMG_PATH.$list['headimage'];
        $list['send_time'] = date('Y-m-d h:i:s',$list['send_time']);
        //订单商品
        $goods = db('order_goods')->where(['order_id'=>$list['order_id']])->field('goods_id,goods_num,goods_name,goods_image')->select();
        foreach($goods as $k=>&$v){
            $v['goods_image'] = IMG_PATH.$v['goods_image'];
        }
        $list['goods'] = $goods;
        $result['info'] = $list;
        return $result;
    }

    //评论回复
    public function reply()
    {
        $uid = $this->user['id'];
        $comment_id = $this->requestData['id'];
        $content = $this->requestData['content'];
        $where['driver_id'] = $uid;
        $where['id'] = $comment_id;
        if(!db('driver_order_comment')->where($where)->find())return ['message'=>'没有权限回复该评论！'];
        $data = [
            'answer'=>$content
        ];
        $res = db('driver_order_comment')->where(['id'=>$comment_id])->update($data);
        if($res)return array();
        return ['message'=>'回复失败!'];
    }

    //司机平均分
    public function score()
    {
        $uid = $this->user['id'];
        $grade = db('driver_order_comment')->where(['driver_id'=>$uid])->avg('grade');
        $result = floor($grade, 2);
        return $result;
    }

    //订单通知
    public function orderTips()
    {
        $uid = $this->user['id'];
//        die($uid);
        $page=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $limit=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $where['status'] = 0;
        $result = $this->getDrivarOrder($uid,$where,$page,$limit);
        return $result;
    }

    public function orderTipinfo()
    {
        $uid = $this->user['id'];
        $id = isset($this->requestData['id'])?$this->requestData['id']:'0';
        if($id){
            $sel = db('driver_order')->where(['id'=>$id])->find();
            if(!$sel) return ['message'=>'数据不存在'];
            if($sel['driver_id'] !=0 && $sel['driver_id'] != $uid){
                return ['message'=>'无权查看'];
            }
//            echo db('driver_order')->getLastSql();
//            var_dump($sel);
//            die;
        }else{
            return ['message'=>'id必传!'];
        }
        $order = db('driver_order_info')->where(['driver_order_id'=>$id])->order('num asc')->select();

        foreach($order as $k=>&$v){
            $v['order'] = db('order')->where(['id'=>$v['order_id']])->field('id,address,lng,lat,mobile,realname,send_status')->find();
        }
        return array('list' => array_merge($order));
    }

    //接单
    public function orderTake()
    {
        $id = $this->requestData['id'];//线路订单id
        $uid = $this->user['id'];//司机id

        $order = db('driver_order')->where(['id'=>$id])->find();
        if(empty($order))return ['message'=>'非法id!'];
        if($order['status'] == 1)return ['message'=>'该单已被接单!'];
        if($order['driver_id'] !=0 ){
            if($order['driver_id'] != $uid)return ['message'=>'无权接单'];
        }
        $shop_id = $order['shop_id'];
        $driver = db('driver_shop')->where(['driver_id'=>$uid,'shop_id'=>$shop_id,'status'=>1,'isbind'=>1])->find();
        if(empty($driver))return ['message'=>'你不是该商家司机'];

        if($order['driver_id'] ==0){
            $data['driver_id'] = $uid;
        }
        $data['status'] = 1;
        $data['take_time'] = TIMESTAMP;

        $distance = db('driver_order_info')->where(['driver_order_id'=>$id])->value('distance');

        //起步价
        $starting_price = db('config')->where(['id'=>'9'])->value('value');

        //起步公里
        $starting_kilometers = db('config')->where(['id'=>'10'])->value('value');

        //超过起步按每公里算
        $exceed = db('config')->where(['id'=>'11'])->value('value');

        if($starting_kilometers <= $distance){
            $data['moeny'] = $starting_price;
        }else{
            $data['moeny'] = $starting_price + ($exceed * $distance);
        }

        $res = db('driver_order')->where(['id'=>$id])->update($data);
        if(!$res)return ['message'=>'接单失败!'];
    }

    //不接单
    public function orderunTake()
    {
        $id = $this->requestData['id'];//线路订单id
        $status = $this->requestData['status'];//线路订单id
        $uid = $this->user['id'];//司机id

        $order = db('driver_order')->where(['id'=>$id])->find();
        if(empty($order))return ['message'=>'非法id!'];
        if($order['status'] == 1)return ['message'=>'该单已被接单!'];
        if($order['driver_id'] !=0 ){
            if($order['driver_id'] != $uid)return ['message'=>'无权拒接单'];
        }
        $shop_id = $order['shop_id'];
        $driver = db('driver_shop')->where(['driver_id'=>$uid,'shop_id'=>$shop_id,'status'=>1,'isbind'=>1])->find();
        if(empty($driver))return ['message'=>'你不是该商家司机'];

        $data['status'] = -1;
        $data['driver_id'] = 0;
        $res = db('driver_order')->where(['id'=>$id])->update($data);
        if(!$res)return ['message'=>'拒接单失败!'];
    }

    public function getDrivarOrder($uid, $where, $page, $limit)
    {
        $where['driver_id'] = [['=',$uid],['=',0],'or'];

        //订单数量
        $count = db('driver_order')->where($where)->count();

        $order = db('driver_order')
            ->where($where)
            ->order('id desc')
            ->page($page,$limit)
            ->select();
//         ECHO $this->getLastSql();EXIT;
        foreach($order as $key=>&$value){
            $value['route_sn'] = db('route')->where(['id'=>$value['route_id']])->value('route_sn');
            $value['shop_info'] = db('shop')->where(['id'=>$value['shop_id']])->field('id,shopname,province,city,county,street,address,mobile,headimage,lng,lat,realname')->find();
            $value['shop_info']['headimage'] = IMG_PATH.$value['shop_info']['headimage'];
            $value['send_time'] = date('Y-m-d h:i:s',$value['send_time']);
            //订单数量
            $value['order_count'] = db('driver_order_info')->where(['driver_order_id'=>$value['id']])->count();
        }
        return array('list' => array_merge($order), 'page_num' => $page, 'page_limit' => $limit, 'count' => $count);
    }

    public function is_empty_unfinish_order($order_id){
//        $order_id = $this->requestData['id'];
        if(!isset($order_id))return false;
        $driver_order_id = db('driver_order_info')->where(['order_id'=>$order_id])->value('driver_order_id');
        if(!$driver_order_id)return false;
        $order_id_list = db('driver_order_info')->where(['driver_order_id'=>$driver_order_id])->column('order_id');
        $where['id'] = ['in', $order_id_list];
        $where['send_status'] = ['<>', 3];
        $count = db('order')->where($where)->count();
        $data['id'] = $driver_order_id;
        if(!$count){
            if($driver_order_id) {
                $driver_order_data = [
                    'finish_time' => TIMESTAMP,
                    'status' => 2
                ];
                db('driver_order')->where(['id' => $driver_order_id])->update($driver_order_data);
            }
        }
    }

}